<template>
	<view v-if="shareInfoStatus" class="poster-first">
	    <view class="mask-share">
			<view class="bg"></view>
			<!-- <image :src="adminUrl+'/crmebimage/public/images/share-info.png'" @click="shareInfoClose" @touchmove.stop.prevent="false"></image> -->
			<view class="share-box acea-row row-middle">
				<view v-if="showShareImg" :style="{width: canvasWidth + 'px', height: canvasHeight + 'px' }">
					<wxml-to-canvas v-if="showCanvas" class="widget" :width="canvasWidth" :height="canvasHeight"></wxml-to-canvas>
					<image v-if="!showCanvas" class="canvasImage" :show-menu-by-longpress="true" :src="canvasImg" :width="canvasWidth" :height="canvasHeight" @click="getpreviewImage"></image>

					<!-- 分享按钮 -->
					<view class="generate-posters on" >
						<view class="generateCon acea-row row-middle">
							<!-- #ifdef MP -->
							<button class="item wxitem" hover-class="none" open-type="share">
								<view class="pictrue">
									<text class="iconfont icon-weixin2"></text>
								</view>
								<view class="">发送给好友</view>
							</button>
							<!-- #endif -->
							<!-- #ifdef MP  -->
							<button class="item hbitem" hover-class="none" @click="extraImage">
								<view class="pictrue">
									<text class="iconfont icon-tupian"></text>
								</view>
								<view class="">生成海报</view>
							</button>
							<!-- #endif -->
						</view>
						<view class="generateClose acea-row row-center-wrapper" @click="shareInfoClose">返回</view>
					</view>
					
				</view>
				<view class="msg-box" v-else :style="{width: canvasWidth + 'px', height: canvasHeight + 'px' }">
				      {{sharemsg}}
				</view>
			</view>
	    </view>
	  </view>
</template>

<script>
// import {getUnlimitedQRCode} from '@/api/api.js'
const { wxml, style } = require('./share.js')
export default {
	props: {
		 shareInfoStatus: {
		      type: Boolean,
		      default:false,
		    },
		showData:{
			type:Object,
			default:()=>{
				return;
			}
		}
	},
  data: function() {
    return {
      adminUrl:this.$config.HTTP_ADMIN_URL,
	  logoUrl:'',
	  ewmImgUrl:'',
	  canvasWidth:320,
	  	canvasHeight:480,
	  	screenWidth: null, // 设备宽度
	  	widget: null,
	  	sharemsg:'加载中，请稍等...',//分享错误信息
	  	showShareImg:false,//是否显示分享图片
	  	showCanvas:true,//是否显示画布
	  	canvasImg:'',
		timeOutEvent:0,//定时器
	  
    };
  },
  mounted: function() {
  },
  methods: {
	  // 图片预览；
	  getpreviewImage: function() {
	  	if (this.canvasImg) {
	  		let photoList = [];
	  		photoList.push(this.canvasImg)
	  		uni.previewImage({
	  			urls: photoList,
	  			current: this.canvasImg
	  		});
	  	} else {
	  		this.$util.Tips({
	  			title: '您的海报尚未生成'
	  		});
	  	}
	  },
	  
	  // 分享给好友
	shareToFriend(){
		// console.log('this.canvasImg',this.canvasImg)
		uni.share({
			provider: "weixin",
			scene: "WXSceneSession",
			type: 2,
			imageUrl: this.canvasImg,
			success: function (res) {
				console.log("success:" + JSON.stringify(res));
			},
			fail: function (err) {
				console.log("fail:" + JSON.stringify(err));
			}
		});
	},
	  // 关闭分享
    shareInfoClose: function() {
		this.$set(this,'showCanvas',true)
		this.$set(this,'canvasImg','')
		uni.hideLoading()
		this.$emit("setShareInfoStatus");
    },
	// 生成二维码；
	make(path,scene) {
		let that = this;
		let data = {
			envVersion:'release',//正式版为 "release"，体验版为 "trial"
			checkPath: false,
			width: 210,
			page: path,
			scene: decodeURIComponent(scene),
			autoColor: true,
			isHyaline: true,
			lineColorVo:{b:255,g:255,r:255}
		}
		getUnlimitedQRCode(data).then(res => {
			that.$set(that,'ewmImgUrl',res.data.code)
			that.getSystemInfo()
		}).catch(err => {
			that.sharemsg = err;
		});
	},
	// 获取系统信息
	getSystemInfo(){
		let platform = uni.getSystemInfoSync().platform
		uni.getSystemInfo({
			success: (res) =>{
				console.log('res',res)
			  this.$set(this,'screenWidth',res.screenWidth)
			  this.$set(this,'canvasWidth',this.screenWidth * 0.9)
			  this.$set(this,'canvasHeight',platform == 'android'? this.screenWidth*1.5:this.screenWidth * 1.4)
			  this.$set(this,'showShareImg',true)
			  // 数字容器宽度 动态设置 
			  setTimeout(() => {
				uni.showLoading({title: '海报生成中...'})
				this.widget = this.selectComponent('.widget')
				// console.log('widget',this.widget)
				this.renderToCanvas()
			  }, 1000)
			}
		});
	},
	// wxml 转 canvas
	renderToCanvas () {
	  const _wxml = wxml(this.showData, this.ewmImgUrl, this.adminUrl)
	  const _style = style(this.screenWidth, this.canvasWidth, this.canvasHeight)
	  // console.log('_wxml',_wxml)
	  // console.log('_style',_style)
	  const p1 = this.widget.renderToCanvas({ wxml: _wxml, style: _style })
	  p1.then((res) => {
		console.log('海报生成成功');
		uni.hideLoading()
		// this.container = res
		this.canvasToImg()
	  }).catch((err) => {
		console.log('生成失败')
		uni.hideLoading()
	  })
	},
				// 画布生成图片
	canvasToImg(){
		if (!this.showShareImg) {
		  uni.showToast({title: '海报生成失败，无法分享到朋友圈', icon: 'none'})
		  return
		}
		const p2 = this.widget.canvasToTempFilePath()
		// console.log('p2',p2)
		p2.then(result => {
		  let path = result.tempFilePath
		  this.$set(this,'canvasImg',path)
		  this.$set(this,'showCanvas',false)
		}).catch((err) => {
			console.log('图片生成失败')
		  })
	},
	// 保存到朋友圈
	extraImage() {
		if (!this.showShareImg) {
		  uni.showToast({title: '海报生成失败，无法分享到朋友圈', icon: 'none'})
		  return
		}
		let that = this
		  let path = this.canvasImg
		  uni.getSetting({
			success: res => {
			  // 非初始化且未授权的情况，需要再次弹窗提示授权
			  if (res.authSetting['scope.writePhotosAlbum'] != undefined && res.authSetting['scope.writePhotosAlbum'] != true) {
				uni.showModal({
				  title: '是否授权相册权限',
				  content: '需要获取相册权限，请确认授权，否则无法使用相关功能',
				  success: res => {
					if (res.confirm) {
					  uni.openSetting({
						success: dataAu => {
						  if (dataAu.authSetting["scope.writePhotosAlbum"] == true) {
							uni.showToast({
							  title: '授权成功',
							  icon: 'none',
							  duration: 1000
							});
							that.saveIMg(path);
						  } else {
							uni.showToast({
							  title: '授权失败',
							  icon: 'success',
							  duration: 1000
							});
						  }
						}
					  });
					}
				  }
				});
			  } else {
				// 初始化且未授权，系统默认会弹窗提示授权
				// 非初始化且已授权，也会进入这里
				that.saveIMg(path);
			  }
			}
		  });
	},
	 // 保存到相册
	async saveIMg (tempFilePath) {
				uni.saveImageToPhotosAlbum({
				  filePath: tempFilePath,
				  success: async (res) => {
					uni.showModal({
					  content: '图片已保存，分享给好友吧！',
					  showCancel: false,
					  confirmText: '好的',
					  confirmColor: '#333',
					  success: function (res) {
						this.setShareInfo()
					  },
					  fail: function (res) {
						console.log('res', res);  
					  }
					});
				  },
				  fail: function (res) {
					uni.showToast({
					  title: '您取消了授权',
					  icon: 'none',
					  duration: 2000
					})
				  }
				});
	 },
					
  }
};

</script>

<style scoped lang="scss">
	.poster-first {
	  overscroll-behavior: contain;
	}
	.widget{
		opacity: 0;
	}
	.mask-share {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  z-index: 999;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  .bg{
		  width: 100%;
		  height: 100%;
		  background-color: rgba(0, 0, 0, 0.6);
		  position: absolute;
		  top: 0;
		  left: 0;
	  }
	  .share-box{
		  width: 90%;
		  position: relative;
		  text-align: center;
		  margin-top: -400rpx;
		  .share-main{
			  width: 100%;
			  border: 20rpx solid #D1A791;
			  background-color: #fff;
			  padding: 25rpx;
			  .logo{
				  width: 165rpx;
				  height: 40rpx;
				  // background-color: #D1A791;
			  }
			  .img{
				  width: 100%;
				  height: 410rpx;
				  margin: 20rpx 0;
				  // background-color: #D1A791;
			  }
			  .title{
				  font-size: 32rpx;
				  text-align: center;
				  line-height: 52rpx;
				  font-weight: bold;
				  text{
					  display: block;
					  width: 90%;
					  margin: auto;
				  }
			  }
			  .ewm{
				  text-align: center;
				  .imgs{
					  width: 420rpx;
					  height: 420rpx;
					  margin: 20rpx auto;
					  text-align: center;
				  }
				  .name{
					  font-size: 24rpx;
					  color: #999999;
				  }
			  }
		  }
		  .close{
			  margin-top: 40rpx;
			  text-align: center;
			  .iconfont{
				 font-size: 70rpx;
				 color: #fff;
				  
			  }
		  }
	  }
	}
	.mask-share image {
	  width: 100%;
	  height:100%;
	}
	.generate-posters {
		width: 100%;
		height: 318rpx;
		background-color: #fff;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 388;
		transform: translate3d(0, 100%, 0);
		transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
		border-top: 2rpx solid #eee;
		
		.generateCon {
			height: 220rpx;
		}
		
		.generateClose {
			height: 98rpx;
			font-size: 32rpx;
			color: #000;
			border-top: 1px solid #eee;
		}
		
		.item {
			.pictrue {
				width: 96rpx;
				height: 96rpx;
				line-height: 96rpx;
				border-radius: 50%;
				margin: 0 auto 6rpx auto;
				image {
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}
				.iconfont{
					color: #ffffff;
					font-size: 48rpx;
				}
			}
		}
		.wxitem{
			.pictrue{
				background-color: #5eae72;
			}
		}
		.hbitem{
			.pictrue{
				@include main-bg-color(theme)
			}
		}
	}
	
	.generate-posters.on {
		transform: translate3d(0, 0, 0);
	}
	
	.generate-posters .item {
		flex: 1;
		text-align: center;
		font-size: 30rpx;
	}
	
	.generate-posters .item .iconfont {
		font-size: 80rpx;
		color: #5eae72;
	}
	
	.generate-posters .item .iconfont.icon-haibao {
		color: #5391f1;
	}
	
	.generate-posters .item .iconfont.icon-haowuquan1 {
		color: #ff954d;
	}
	
</style>
